package net.mikoo.seals.manage.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import net.mikoo.seals.biz.service.ApplyServices;
import net.mikoo.seals.biz.service.DevicesActService;
import net.mikoo.seals.biz.service.DevicesUsedServices;
import net.mikoo.seals.biz.service.VerifyService;
import net.mikoo.seals.common.WebContext;
import net.mikoo.seals.common.enums.ApplyStatusEnum;
import net.mikoo.seals.common.enums.ApplyTypeEnum;
import net.mikoo.seals.common.enums.UsedStatusEnum;
import net.mikoo.seals.common.enums.VerifyStatusEnum;
import net.mikoo.seals.common.model.PageModel;
import net.mikoo.seals.manage.web.common.BaseController;
import net.mikoo.seals.model.Apply;
import net.mikoo.seals.model.ApplyQuery;
import net.mikoo.seals.model.ApplyVerify;
import net.mikoo.seals.model.ApplyVerifyQuery;
import net.mikoo.seals.model.DevicesAct;
import net.mikoo.seals.model.DevicesActQuery;
import net.mikoo.seals.model.DevicesUsed;
import net.mikoo.seals.model.DevicesUsedCert;
import net.mikoo.seals.model.DevicesUsedQuery;
import net.mikoo.seals.model.Upfile;
import net.mikoo.seals.utils.DateUtil;
import net.mikoo.seals.utils.ExcelUtil;

@Controller
@RequestMapping("/record")
public class RecordController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(RecordController.class);

	@Autowired
	private ApplyServices applyServices;
	
	@Autowired
	private VerifyService verifyService;
	
	@Autowired
	private DevicesActService devicesActService;
	
	@Autowired
	private DevicesUsedServices devicesUsedServices;
	
	
	/**
	 * 申请列表
	 * 
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/applyList")
	public String applyList(ApplyQuery query, HttpServletRequest request, Model model) {

		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);

		query.setSealId(query.getSealId());
		query.setCompanyId(companyId);

		PageModel<Apply> pm = applyServices.getPageByQuery(query);
		model.addAttribute("pm", pm);
		model.addAttribute("query", query);
		return "record/applyList";
	}
	/**
	 * 申请详情
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/applyInfo")
	public String applyInfo(ApplyQuery query, HttpServletRequest request, Model model) {
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		query.setCompanyId(companyId);
		Apply  apply =  applyServices.getInfoByQuery(query);
		
		List<Upfile> upfiles = applyServices.getApplyfiles(apply.getApplyId());
		
		ApplyVerifyQuery vquery = new ApplyVerifyQuery();
		vquery.setCompanyId(companyId);
		vquery.setApplyId(apply.getApplyId());
		List<ApplyVerify> verifys = verifyService.getListByQuery(vquery);
		
		model.addAttribute("apply", apply);
		model.addAttribute("upfiles", upfiles);
		model.addAttribute("verifys", verifys);
		return "record/applyInfo";
	}
	
	@RequestMapping("/approveList")
	public String approveList(DevicesActQuery query, HttpServletRequest request, Model model) {

		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		//Long partyId = getCurrentPartyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		query.setCompanyId(companyId);
		//query.setPartyId(partyId);
		PageModel<DevicesAct> pm = devicesActService.getActPageByQuery(query);
		model.addAttribute("pm", pm);
		model.addAttribute("query", query);
		
		return "record/approveList";
	}
	
	
	@RequestMapping("/approveInfo")
	public String approveInfo(DevicesActQuery query, HttpServletRequest request, Model model) {

		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		query.setCompanyId(companyId);
		
//		query.setCompanyId(companyId);
		//query.setCustosPartyId(partyId);
		DevicesAct devicesAct = devicesActService.getInfoByQuery(query);
		model.addAttribute("devicesAct", devicesAct);
		
		ApplyQuery applyQuery = new ApplyQuery();
		applyQuery.setCompanyId(companyId);
		applyQuery.setApplyId(devicesAct.getApplyId());
		Apply apply = this.applyServices.getInfoByQuery(applyQuery);
		model.addAttribute("apply", apply);
		
		List<Upfile> applyFiles = applyServices.getApplyfiles(devicesAct.getApplyId());
		model.addAttribute("applyFiles", applyFiles);
		
		ApplyVerifyQuery verifyQuery  = new ApplyVerifyQuery();
		verifyQuery.setApplyId(devicesAct.getApplyId());
		verifyQuery.setCompanyId(companyId);
		List<ApplyVerify> verifys = verifyService.getListByQuery(verifyQuery);
		model.addAttribute("verifys", verifys);
		
		
		DevicesUsedQuery usedQuery = new DevicesUsedQuery();
		usedQuery.setCompanyId(companyId);
		usedQuery.setDevicesActId(devicesAct.getDevicesActId());
		List<DevicesUsed> useds = devicesUsedServices.getListByQuery(usedQuery);
		model.addAttribute("useds", useds);
		
		
		List<DevicesUsedCert> usedCerts = devicesUsedServices.getCertsByDevicesActId(devicesAct.getDevicesActId());
		model.addAttribute("usedCerts", usedCerts);
		
		
		
		return "record/approveInfo";
	}
	
	

	@RequestMapping("/usedList")
	public String usedList(DevicesUsedQuery query, HttpServletRequest request, Model model) {

		
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		query.setCompanyId(companyId);

		PageModel<DevicesUsed> pm = devicesUsedServices.getPageByQuery(query);
		model.addAttribute("pm", pm);
		model.addAttribute("query", query);
		return "record/usedList";
	}
	
	
	@RequestMapping("/usedInfo")
	public String usedInfo(DevicesUsedQuery query, HttpServletRequest request, Model model) {
		
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		query.setCompanyId(companyId);
		
		DevicesUsed used = devicesUsedServices.getInfoByQuery(query);
		
		ApplyQuery applyQuery = new ApplyQuery();
		applyQuery.setApplyId(used.getApplyId());
		Apply apply = applyServices.getInfoByQuery(applyQuery);
		
		ApplyVerifyQuery verifyQuery = new  ApplyVerifyQuery();
		verifyQuery.setCompanyId(companyId);
		verifyQuery.setApplyId(apply.getApplyId());
		List<ApplyVerify> verifys =  verifyService.getListByQuery(verifyQuery);
		
		List<DevicesUsedCert> usedCerts = devicesUsedServices.getCertsByQuery(query);
		
		model.addAttribute("used", used);
		model.addAttribute("apply", apply);
		model.addAttribute("verifys", verifys);
		model.addAttribute("usedCerts", usedCerts);
		
		return "record/usedInfo";
	}
	
	
	//导出
		@RequestMapping("/applyExport")
		public void applyExport(ApplyQuery query,HttpServletRequest request,HttpServletResponse response) throws IOException{  
			
  
			
			Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
			query.setCompanyId(companyId);
			List<Apply> applys = applyServices.getListByQuery(query);
			
			
			//excel标题
			String[] title = {"申请时间","类型","申请人","印章","申请次数","状态","审核结果"};
			
			//excel文件名
	    	String fileName = "applys"+System.currentTimeMillis()+".xls";
			
	    	String sheetName = "申请记录表";
			
			String content[][] = new String[applys.size()][title.length];
			
	    	for (int i = 0; i < applys.size(); i++) {
	            Apply obj = applys.get(i);
	            content[i][0] = DateUtil.formate(obj.getApplyTime(), "yyyy-MM-dd HH:mm:ss");
	            content[i][1] = ApplyTypeEnum.getByCode(obj.getApplyType()).getMessage();
	            content[i][2] = obj.getPerson().getName();
	            content[i][3] = obj.getSeal().getSealName();
	            content[i][4] = obj.getApplyTimes()+"";
	            content[i][5] = ApplyStatusEnum.getByCode(obj.getApplyStatus()).getMessage();
	            
	            
	            String str = "";
	            List<ApplyVerify> verifys  = obj.getVerifys();
	            if(verifys !=null && !verifys.isEmpty()) {
	            	
	            	for (int j = 0; j < verifys.size(); j++) {
	            		ApplyVerify verify = verifys.get(j);
	            		String name = verify.getPerson().getName();
		            	String time = DateUtil.formate(verify.getVerifyTime(), "yyyy-MM-dd HH:mm:ss");
		            	String status = VerifyStatusEnum.getByCode(verify.getVerifyStatus()).getMessage();
		            	String result = verify.getVerifyResult();
		            	if(j>0) {
		            		str += "->";
		            	}
		            	str += "("+time+" "+name+" "+status+" "+result+")";
					}
		            content[i][6] = str;
	            }
	            
	            
	    	}
			
			
	    	HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
	    	
	    	try {
	            response.setContentType("application/octet-stream;charset=UTF-8");
	            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
	            response.addHeader("Pargam", "no-cache");
	            response.addHeader("Cache-Control", "no-cache");
	            
	            OutputStream os = response.getOutputStream();
	        	wb.write(os);
	        	os.flush();
	        	os.close();
	            
	        } catch (Exception ex) {
	            ex.printStackTrace();
	        }
	    	
		}  
	
	//导出
	@RequestMapping("/usedExport")
	public void usedExport(DevicesUsedQuery query,HttpServletRequest request,HttpServletResponse response) throws IOException{  
		
//		InputStream  in = servletContext.getResourceAsStream("/temp/stafftemp.xls");
//		
//		byte[] data = FileUtil.toByteArray(in);
//		
//	    response.reset();  
//	    response.setHeader("Content-Disposition", "attachment; filename=stafftemp.xls");  
//	    response.addHeader("Content-Length", "" + data.length);  
//	    response.setContentType("application/octet-stream;charset=UTF-8");  
//	    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
//	    outputStream.write(data);  
//	    outputStream.flush();  
//	    outputStream.close();  
		
		Long companyId = getCompanyId(request, WebContext.ADMIN_LOGIN_SESSION_KEY);
		query.setCompanyId(companyId);
		List<DevicesUsed> useds = devicesUsedServices.getListByQuery(query);
		
		
		//excel标题
		String[] title = {"时间","类型","申请人","印章","设备","凭证","状态"};
		
		//excel文件名
    	String fileName = "useds"+System.currentTimeMillis()+".xls";
		
    	String sheetName = "使用记录表";
		
		String content[][] = new String[useds.size()][title.length];
		
    	for (int i = 0; i < useds.size(); i++) {
            DevicesUsed obj = useds.get(i);
            content[i][0] = DateUtil.formate(obj.getUsedTime(), "yyyy-MM-dd HH:mm:ss");
            content[i][1] = ApplyTypeEnum.getByCode(obj.getApplyType()).getMessage();
            content[i][2] = obj.getPerson().getName();
            content[i][3] = obj.getSeal().getSealName();
            content[i][4] = obj.getDevices().getDevicesCode();
            content[i][5] = obj.getVoucherUrl();
            content[i][6] = UsedStatusEnum.getByCode(obj.getUsedStatus()).getMessage();
    	}
		
		
    	HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
    	
    	try {
           	fileName = new String(fileName.getBytes(),"UTF-8");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            
            OutputStream os = response.getOutputStream();
        	wb.write(os);
        	os.flush();
        	os.close();
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    	
	}  
	
	
	
	
	

}
